<template>
  <el-dialog
    class="public-dialog"
    title="导入期初余额"
    width="720"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <Upload
        label="Excel文件"
        require
        :modelValue="fileList"
        @update:modelValue="handleInput"
      >
        <template #headRight>
          <el-button text type="primary" @click.stop="handleDownLoadTemplate">
            <span>下载模板</span>
          </el-button>
        </template>
      </Upload>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import Upload from '@/components/Upload/index.vue'
import {importlogisticsCope} from '../../api/index.js'
import { getImportUrl } from '@/api/public'
const props = defineProps({
  modelValue: { type: Boolean, default: false },
})
const emit = defineEmits(['update:modelValue', 'refresh', 'close'])
const loading = ref()

const handleDownLoadTemplate = async () => {
  const { data } = (await getImportUrl({ type: 'finance.logisticsCope' })) || {}
  const _url = data?.uri
  if (_url) window.open(_url, 'noopener', 'noreferrer')
}

const fileList = ref([])
const handleInput  = (val) =>{
  fileList.value = val
}
const handleSave = async () => {
  try {
    if(!fileList.value?.length) return ElMessage.warning("请先导入文件!")
    const { code, message } = await importlogisticsCope({file:fileList.value[0]?.response})
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success("导入成功!")
    handleClose(true)
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  fileList.value = []
  await nextTick()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
